const config = require('../common/config');
//登录接口
const loginApiModule = require('../api/login');
//token验证
const authModule = require('../common/auth');
//users数据模块
const usersModel = require('../models/users');
const usersService = require('../services/users');
//微信规范加解密
const crypto = require('../utils/crypto');

function login(param) {
  let openidParam = {
    js_code: param.js_code,
    appid: config.APPID,
    secret: config.SECRET,
    grant_type: "authorization_code"
  };
  return new Promise(async (resolve, reject) => {
    try {
      let openidData = await loginApiModule.getSessionKey(openidParam);
      if (openidData.openid) {
        const usersData = await usersModel.byOpenid(openidData.openid);
        if (!usersData._id) {
          let user = {
            openid: openidData.openid,
            roles: [1],
            role: 1
          };
          let addData = await usersService.add(user);
          user._id = addData.id;
          resolve({
            ...user,
            token: openidData.session_key
          })
        } else {
          if (usersData.class.length > 0) {

          }
          resolve({
            ...usersData,
            token: openidData.session_key
          })
        }
      } else {
        reject('获取用户信息失败');
      }
    } catch (error) {
      reject(error);
    }
  })
};

// function phoneLogin(param) {
//   let openidParam = {
//     js_code: param.js_code,
//     appid: config.APPID,
//     secret: config.SECRET,
//     grant_type: "authorization_code"
//   };
//   return new Promise(async (resolve, reject) => {
//     try {
//       let openidData = await loginApiModule.getSessionKey(openidParam);
//       let token = authModule.getToken();
//       let phoneParam = {
//         code: form.code
//       }
//       let phoneData = await loginApiModule.getPhone(phoneParam, token);
//       console.log(phoneData);
//       if (openidData.openid) {
//         const usersData = await usersService.usersById(openidData.openid);
//         if (usersData.data.length <= 0) {
//           let user = {
//             openid: openidData.openid,
//             roles: [1],
//             role: 1
//           };
//           await usersService.usersAdd(user);
//           resolve({
//             ...user,
//             token: openidData.session_key
//           });
//         } else {
//           resolve({
//             ...usersData,
//             token: openidData.session_key
//           });
//         }
//       } else {
//         return throwError('获取用户信息失败');
//       }
//     } catch (error) {
//       reject(error);
//     }
//   })
// }

function checkSessionKey(param) {
  return new Promise(async (resolve, reject) => {
    try {
      let token = await authModule.getToken();
      let sessionParam = {
        access_token: token,
        openid: param.openid,
        signature: crypto.hmacSHA256(param.session_key, ""),
        sig_method: "hmac_sha256"
      }
      let sessionKeyData = await loginApiModule.checkSessionKey(sessionParam);
      resolve(sessionKeyData.errcode);
    } catch (error) {
      reject(error);
    }
  })
}

function getStatusCounts(arr) {
  const total = _.size(arr);
  const completedCount = _.size(_.filter(arr, item => item.status === 1 || item.status === 2));
  const inProgressCount = _.size(_.filter(arr, item => item.status === 3 || item.status === 4));
  return {
    total,
    completedCount,
    inProgressCount
  };
}

module.exports = {
  login,
  checkSessionKey
}